package com.studentmanagement.service;

import com.studentmanagement.dao.UserMapper;
import com.studentmanagement.model.User;
import com.studentmanagement.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserService {
    public User login(String username, String password) {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.login(username, password);
        }
    }
    
    public User getUserById(Integer id) {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.getUserById(id);
        }
    }
    
    public User getUserByUsername(String username) {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.getUserByUsername(username);
        }
    }
    
    public List<User> getAllUsers() {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.getAllUsers();
        }
    }
    
    public boolean insertUser(User user) {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int result = mapper.insertUser(user);
            session.commit();
            return result > 0;
        }
    }
    
    public boolean updateUser(User user) {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int result = mapper.updateUser(user);
            session.commit();
            return result > 0;
        }
    }
    
    public boolean deleteUser(Integer id) {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int result = mapper.deleteUser(id);
            session.commit();
            return result > 0;
        }
    }
} 